package com.qianfeng.smartplatform.operlog;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartplatform.exceptions.BaseException;
import com.qianfeng.smartplatform.operlog.annotations.LogAnnotation;
import com.qianfeng.smartplatform.pojo.MyBaseUser;
import com.qianfeng.smartplatform.pojo.SysOperLog;
import com.qianfeng.smartplatform.utils.RequestUtil;
import com.qianfeng.smartplatform.utils.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Created by Jackiechan on 2022/6/8 9:36
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Aspect
@Component
public class LogAdvice {

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    //声明切入点表达式,拦截的是带有我们指定的某个注解的方法
    @Pointcut("@annotation(com.qianfeng.smartplatform.operlog.annotations.LogAnnotation)")
    public void pointcut() {
    }

    @AfterReturning(value = "pointcut()", returning = "result")
    public void after(JoinPoint joinPoint, Object result) {
        SysOperLog sysOperLog = new SysOperLog();
        //当前方法是没有异常的方法
        sysOperLog.setStatus(1L);
        sysOperLog.setErrorMsg("200 OK");

        //返回结果的json
        try {
            String resultJson = objectMapper.writeValueAsString(result);
            sysOperLog.setJsonResult(resultJson);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        addLog(joinPoint,sysOperLog);
    }

    //当出现异常的情况下会执行这个
    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        SysOperLog sysOperLog = new SysOperLog();
        //当前方法是没有异常的方法
        sysOperLog.setStatus(0L);
        if (e instanceof BaseException) {
            sysOperLog.setErrorMsg(((BaseException) e).getCode() + e.getMessage());
        } else {
            sysOperLog.setErrorMsg(e.getMessage());
        }
        addLog(joinPoint,sysOperLog);
    }


    public void addLog(JoinPoint joinPoint,SysOperLog sysOperLog) {
        //获取到用户名
        MyBaseUser baseUser = SecurityUtils.getUserInfo(false);
        if (baseUser != null) {
            sysOperLog.setOperName(baseUser.getUsername());
        }
        //获取到request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //异步运行
        CompletableFuture.runAsync(() -> {
            //请求方式
            String requestMethod = request.getMethod();
            sysOperLog.setRequestMethod(requestMethod);
            //获取到请求的地址
            String requestURI = request.getRequestURI();
            sysOperLog.setOperUrl(requestURI);
            //获取到ip
            String ip = RequestUtil.getRemoteHost(request);
            sysOperLog.setOperIp(ip);
            //获取操作系统
            Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
            //设置客户端
            String os = osAndBrowserInfo.get("os");
            switch (os) {
                case "Android":
                case "IPhone":
                    //设置来自于移动端
                    sysOperLog.setOperatorType(2L);
                    break;
                case "Windows":
                case "Mac":
                case "Unix":
                    //设置来自于PC端
                    sysOperLog.setOperatorType(1L);
                    break;
                default:
                    //设置来自于其他端
                    sysOperLog.setOperatorType(0L);
                    break;
            }

            //获取方法的名字
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            String methodName = signature.getName();
            sysOperLog.setMethod(methodName);
            //方法上有注解,注解中有我们需要的一些数据
            Method method = signature.getMethod();
            LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
            if (logAnnotation != null) {
                String title = logAnnotation.title();
                long businessType = logAnnotation.businessType();
                sysOperLog.setTitle(title);
                sysOperLog.setBusinessType(businessType);
            }


            //获取到请求的参数.参数都在方法中
            Object[] args = joinPoint.getArgs();
            try {
                sysOperLog.setOperParam(objectMapper.writeValueAsString(args));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            //获取到地址
            String locationByIp = RequestUtil.getLocationByIp(ip);
            sysOperLog.setOperLocation(locationByIp);
            //操作时间
            Date operTime = new Date();
            sysOperLog.setOperTime(operTime);
            System.err.println(sysOperLog);

            //TODO 插入到数据库
        });
    }
}
